import { get, post } from './httpRequest'
import api from '../fake/api'
import es6 from 'es6-promise'
import config from '../etc/config'

const dev = config.dev

function proxy(url, data, method, callback, cashe) {
  const fake = api[url]
  if (fake && fake.use) {
    console.log(method + ' proxy ' + url, data)
    return new es6.Promise((resolve, reject) => {
      resolve(fake.callback(url, data, method))
    })
  } else {
    url = url.replace('api.douban.com', 'douban.uieee.com')
    const res = cashe ? wx.getStorageSync('http-cashe-' + url) : null
    if (res) {
      console.log(method + ' cashe ' + url, data)
      return new es6.Promise((resolve, reject) => {
        resolve(res)
      })
    } else {
      console.log(method + ' request ' + url, data)
      // 感谢 https://github.com/zce/douban-api-proxy 支持
      return callback(url, data, cashe)
    }
  }
}

function doGet(url, data, cashe = dev) {
  return proxy(url, data, 'GET', get, cashe)
}

function doPost(url, data, cashe = dev) {
  return proxy(url, data, 'POST', post, cashe)
}

export {
  doGet,
  doPost
}